﻿<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="AlterForm.aspx.cs" Inherits="iSun.WebApp.DesignForm.AlterForm" %>
<%@ Register Assembly="CKEditor.NET" Namespace="CKEditor.NET" TagPrefix="CKEditor" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
    <title></title>
    <!--CSS file (default YUI Sam Skin) -->
    <link rel="stylesheet" type="text/css" href="../scripts/yui_2.9.0/build/reset-fonts-grids/reset-fonts-grids.css" />
   <link rel="stylesheet" type="text/css" href="../scripts/yui_2.9.0/build/container/assets/skins/sam/container.css" />
    <link href="../Styles/table_style.css" rel="stylesheet" type="text/css" />
   <link rel="stylesheet" type="text/css" href="../scripts/yui_2.9.0/build/menu/assets/skins/sam/menu.css" />
   <link rel="stylesheet" type="text/css" href="../scripts/yui_2.9.0/build/button/assets/skins/sam/button.css" />
    <link rel="stylesheet" type="text/css" href="../scripts/yui_2.9.0/build/resize/assets/skins/sam/resize.css" />
    <link rel="stylesheet" type="text/css" href="../scripts/yui_2.9.0/build/layout/assets/skins/sam/layout.css" />
 <link type="text/css" rel="stylesheet" href="../Scripts/yui_2.9.0/build/datatable/assets/skins/sam/datatable.css" />
    <!--begin custom header content for this example-->
    <style type="text/css">
        .yui-skin-sam table {
	    width: 100%;
            margin-bottom: 0px;
        }
    
    #button-example-form fieldset, 
    #button-example-form fieldset div {

        border: 2px groove #ccc;
        margin: .5em;
        padding: .5em;

    }

    .yui-button#pushbutton2 button,
    .yui-button#pushbutton5 button, 
    .yui-button .Add button {
        background: url(../button/assets/add.gif) center center no-repeat;
        text-indent: -4em;
        overflow: hidden;
        padding: 0 .75em;
        width: 2em;
        *margin-left: 4em;   /* IE only */
        *padding: 0 1.75em;  /* IE only */

    }
    
    .yui-button#pushbutton3 button,
    .yui-button#pushbutton6 button, 
    .yui-button#pushbutton9 button {

        padding-left: 2em;
        background: url(../button/assets/add.gif) 10% 50% no-repeat;
    
    }
    #container select,#container input
    {
        width:100%;
        min-width:5em;
    }
    
    
    #toolbar
    {
        border-bottom:1px solid #ccc;
        margin-bottom:3px;
    }
    .form
    {
        padding:5px;
    }
    
    .form select
    {
        width:120px;
    }
    
    
        .style1
        {
            width: 52px;
        }
        .style2
        {
            width: 138px;
        }
        .style4
        {
            width: 41px;
        }
            
    
        .style6
        {
            width: 208px;
        }
    
    
        .style7
        {
            width: 43px;
        }
    
    
        .style8
        {
            width: 48px;
        }
        .style9
        {
            width: 49px;
        }
        .style10
        {
            width: 59px;
        }
    
    
        .style11
        {
            width: 95px;
        }
    
    
    </style>
    

    <!--end custom header content for this example-->
    <!-- Dependencies -->
    <script type="text/javascript" src="../Scripts/yui_2.9.0/build/yahoo-dom-event/yahoo-dom-event.js"></script>
    <script type="text/javascript" src="../Scripts/yui_2.9.0/build/element/element-min.js"></script>
    <script type="text/javascript" src="../Scripts/yui_2.9.0/build/datasource/datasource-min.js"></script>
    <!-- OPTIONAL: JSON Utility (for DataSource) -->
    <script type="text/javascript" src="../Scripts/yui_2.9.0/build/json/json-min.js"></script>
    <!-- OPTIONAL: Connection Manager (enables XHR for DataSource) -->
    <script type="text/javascript" src="../Scripts/yui_2.9.0/build/connection/connection-min.js"></script>
    <!-- OPTIONAL: Get Utility (enables dynamic script nodes for DataSource) -->
    <script type="text/javascript" src="../Scripts/yui_2.9.0/build/get/get-min.js"></script>
    <!-- OPTIONAL: Drag Drop (enables resizeable or reorderable columns) -->
    <script type="text/javascript" src="../Scripts/yui_2.9.0/build/dragdrop/dragdrop-min.js"></script>
    <!-- OPTIONAL: Calendar (enables calendar editors) -->
    <script type="text/javascript" src="../Scripts/yui_2.9.0/build/calendar/calendar-min.js"></script>
    <!-- Source files -->
    <script type="text/javascript" src="../Scripts/yui_2.9.0/build/datatable/datatable-min.js"></script>
    <script type="text/javascript" src="../scripts/yui_2.9.0/build/layout/layout-min.js"></script>
    <script type="text/javascript" src="../scripts/yui_2.9.0/build/button/button-min.js"></script>
    <script type="text/javascript" src="../scripts/yui_2.9.0/build/container/container-min.js"></script>
    <script type="text/javascript" src="../scripts/yui_2.9.0/build/resize/resize-min.js"></script>
    <script src="../Scripts/Appjs/model.TrSubjectInfo.js" type="text/javascript"></script>
    <script src="../ckeditor/ckeditor.js" type="text/javascript"></script>
    <script src="../Scripts/jquery-1.6.min.js" type="text/javascript"></script>
    <script src="../Scripts/jquery.json-2.2.min.js" type="text/javascript"></script>
    <script src="../Scripts/Jquery/jlinq/jlinq.js" type="text/javascript"></script>
    <script src="../Scripts/Jquery/DesignForm/DesignForm.Common.js" type="text/javascript"></script>
    <script src="DesignForm.js" type="text/javascript"></script>
    <script src="../Scripts/Jquery/ComBox/babu.common.js" type="text/javascript"></script>
    <script src="../Scripts/Jquery/ComBox/babu.combobox.js" type="text/javascript"></script>
    <script type="text/javascript">
	//<![CDATA[

        // The instanceReady event is fired, when an instance of CKEditor has finished
        // its initialization.

    </script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
      <div id="contents" class="yui-skin-sam">
        <div id="toolbar" style="padding: 5px;">
            <%--        <button type="button" id="btnOpen" class="yui-button yui-push-button" style="display: none">
            打开方案</button>--%>
             
             <table><tr><td class="style1"> 表单名：</td>
          <td class="style2"><input id="txtFormName"  type="text" onchange="txtFormName_ChangeEvent(this)"  /></td>
                <td class="style7">&nbsp;列数：</td>
          <td class="style4">
          <select name="sctColNum"  id="sctColNum">
            <option value="1">1</option>
            <option value="2">2</option>
            <option value="3">3</option>
            <option value="4">4</option>
           </select>
          </td><td class="style8">表类型：</td>
          <td class="style10"><select name="sctTableType"  id="sctTableType">
            <option value="Master">主表</option>
            <option value="Details">从表</option>
           </select></td><td class="style9">表名：</td>
          <td class="style6"> <input id="setTable" name="setTable" type="text"  style="width:200px" />
              </td><td class="style11"><input id="chkAddDefault" type="checkbox" 
                      checked="checked" />是否加默认值</td><td>
          <button type="button" id="btnSave"  class="yui-button yui-push-button">
                新增表</button></td>
       </tr>
          </table>

            
        </div>
        <div class="form" style="display: none"> 
        </div>
        <div id="divEditor">
          <CKEditor:CKEditorControl ID="CKEditorDesignForm" runat="server" Height="600" >

        </CKEditor:CKEditorControl>
        </div>
         
        <div id="dialog1" class="yui-pe-content" >
        <div class="hd">
            数据表的信息:</div>
        <div class="bd">
            <iframe id="EditUIWindow1" frameborder="0" src="" style="width: 100%; height: 100%;
                margin: 0px; padding: 0px;"></iframe>
        </div>
    </div>
    </div>

      
    
 	



    </div>


    <script type="text/javascript">



        // 字段信息     
        var const_SolutionList = null,
        const_EntityName = '',
        _MasterData = [],
        _DetailsDate = [],
        _PrmaryKey = '',
        _FormID = '<%= FormID%>',
        _FormName = '<%=FormName %>',
        _MasterTableName = '<%=MasterTableName %>',
        _TemplateName = '<%=TemplateName %>',
        _DetailsTableName = '',
        SelecctMasterDatasource = [],
        SelecctDetailsDatasource = [],
        _TemplateName = '<%=TemplateName %>',
        _MasterJson = '',
        _DetailsJson = '<%=DetailsJson %>',
        oCKeditor,
         html = '',
        _SelectArray = null,
         ControlArray = null;

        function cb_onValueChanged(sender, e) {

            var tr = Babu.BrowserHelper.getParentElement(sender.get_element(), "TR");

            var _tablename = sender.__lastText;

            var _value = document.getElementById("setTable").value;
            if (_tablename != "") {
                var _array = _value.split("@");
                const_EntityName = _array[1];

                var _isAddDefault = "0";

                if (document.getElementById("chkAddDefault").checked) { _isAddDefault = "1"; }
                else { _isAddDefault = "0"; }

                document.getElementById("EditUIWindow1").src = "FormTableManager.aspx?tableid=" + _array[0] + "&table=" + _array[1] + "&tablename=" + _tablename + "&AddDefault=" + _isAddDefault + "&r=" + Math.random() + "&entity=SysTable";
                YAHOO.example.container.dialog1.show();
            }
        }
        function disableAddTable(isDisabled) {
            document.getElementById('btnSave ').disabled = isDisabled;
        }

        function getTableType() {
            return document.getElementById("sctTableType").value;
        }
        function createEditor(formName, TableName, strJson, PKeyJson) {
           
            var tableType = document.getElementById("sctTableType").value;
            if (tableType == "Master") {
                if (_MasterTableName != '') {
                    var r = confirm("主表信息存在是否重新加载！")
                    if (r == true) {
                        MastetInit(formName, TableName, strJson);
                    }
                } else {
                    MastetInit(formName, TableName, strJson);
                }
            } else {
                DetailsInit(formName, TableName, strJson, PKeyJson)
            }

        }

        function MastetInit(formName, TableName, strJson) {
            //_SelectArray = new Array();
            _MasterTableName = TableName;
            //DIF.init(_FormID, _FormName, _MasterTableName, _TemplateName);
            var colnum = document.getElementById("sctColNum").value;
            DIF.CodeSmithExplorer.init(formName, TableName, strJson, colnum, 'Master');

        }
        //debugger;
        function DetailsInit(formName, TableName, strJson, keyJson) {
            _DetailsTableName = TableName;

            DIF.DetailsData.init(TableName);
            DIF.CodeSmithExplorer.init(formName, TableName, strJson, '1', 'Details');
            DIF.AddDetailsNewItems(TableName, keyJson);

        }

        $(function () {
            _SelectArray = new Array();
            DIF.init(_FormID, _FormName, _MasterTableName, _TemplateName);
            DIF.DetailsItems.init(_DetailsJson);
            oCKeditor = CKEDITOR.replace('CKEditorDesignForm',
                  {
                      extraPlugins: 'tableresize',
                      extraPlugins: 'onchange'
                  });

            oCKeditor.on('change', function (e) {
                var formHtml = oCKeditor.getData();
                RegularManager(formHtml);
            });
            oCKeditor.on('instanceReady', function (event) {
                var editor = event.editor;
                setTimeout(function () {
                    // Delay bit more if editor is still not ready.
                    if (!editor.element) {
                        setTimeout(arguments.callee, 100);
                        return;
                    }
                    event.removeListener('instanceReady', this.callee);
                    //                    if (editor.name == 'CKEditorDesignForm') {
                    //                        var command = editor.getCommand('maximize');
                    //                        command.exec();
                    //                    }
                }, 0);
            }, null, null, 9999);
            DIF.GetFormFieldItems.init(_FormID);


            YAHOO.namespace("example.container");
            init_selectTable();



            var formName = $("#txtFormName");
            formName.css("border-bottom-style", "none");
            formName.css("border-bottom-color", "transparent");
            formName.css("border-right-style", "none");
            formName.css("border-top-color", "transparent");
            formName.css("border-top-style", "none");
            formName.css("border-right-color", "transparent");
            formName.css("border-left-style", "none");
            formName.css("border-left-color", "transparent");
            formName.css("background", "#f2f8ff");

            formName.attr("readonly", "readonly");
            formName.val(_FormName);

            var tdDatasource = document.getElementById("setTable")
            //tdDatasource.value = _MasterTableName;

            if (tdDatasource.parentNode.lastChild.lastChild.firstChild.firstChild.all[0]) {
                tdDatasource.parentNode.lastChild.lastChild.firstChild.firstChild.all[0].value = _MasterTableName;
            }




            var handleSubmit = function () {

                var editwindow = document.getElementById("EditUIWindow1");
                if (editwindow) {
                    editwindow.contentWindow.Save();
                }
                //this.cancel();
                //init_selectTable();
            };

            var handleCancel = function () {
                this.cancel();
            };

            var handleAddFormSubmit = function () {
                
                var _value = "";
                _value = document.getElementById("setTable").value;
                if (_value == "") {
                    if (document.getElementById("setTable").parentNode.lastChild.lastChild.firstChild.firstChild.all[0]) {
                        _value = document.getElementById("setTable").parentNode.lastChild.lastChild.firstChild.firstChild.all[0].value;
                    }

                    if (_value != "" && _value != null) {
                        var _isAddDefault = "0";

                        if (document.getElementById("chkAddDefault").checked) { _isAddDefault = "1"; }
                        else { _isAddDefault = "0"; }
                        document.getElementById("EditUIWindow1").src = "FormTableManager.aspx?tableName=" + _value + "&table=" + _value + "&AddDefault=" + _isAddDefault + "&r=" + Math.random() + "&entity=SysTable"

                        YAHOO.example.container.dialog1.show();
                    } else { alert("表名不能为空！"); }

                }
            };

            YAHOO.example.container.dialog1 = new YAHOO.widget.Dialog("dialog1",
							    { width: "850px",
							        height: "450px",
							        fixedcenter: true,
							        visible: false,
							        draggable: true,
							        close: true,
							        autofillheight: "body",
							        constraintoviewport: true,
							        buttons: [{ text: "生成表单", handler: handleSubmit, isDefault: true },
								          { text: "取消", handler: handleCancel}]
							    });

            YAHOO.example.container.dialog1.render();

            YAHOO.util.Event.onContentReady("toolbar", function () {
                var btnSave = new YAHOO.widget.Button("btnSave");
                btnSave.on("click", handleAddFormSubmit);

            });

        });






        $(document).ready(function () {
            //
            var formHtml = oCKeditor.getData();
            RegularManager(formHtml);
        });





        function init_selectTable() {
            $.ajax({
                type: "POST",
                url: "TableData.aspx/GetTableNames", //获取主表信息
                data: "{}",
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                async: false,
                success: function (data) {
                    if (data.d) {
                        var items = data.d;
                        var person = JSON.parse(items);
                        createComboBox("setTable", { itemSource: person, style: "dropdown", autoComplete: "local" });
                    }
                },
                error: function (err) {
                    alert(err + "err");
                }
            });


        }
        function formatSelectTable(data) {
            if (data) {
                var person = JSON.parse(data);
                var tbSelecct = document.getElementById("setTable")
                //additemtoselect(tbSelecct, '空', '');
                $.each(person, function (n, value) {
                    //do something here   
                    additemtoselect(tbSelecct, value.TableName, value.TableName);
                });
            }

        }
        function additemtoselect(objselect, objitemtext, objitemvalue) {
            var varitem = new Option(objitemtext, objitemvalue);
            objselect.options.add(varitem);
        }

        function closeWin() {
            YAHOO.example.container.dialog1.hide();
            document.getElementById("setTable").value = "";
        }
        //保存
        var Save = function (myDataTable, TableName, PrimaryKeyItems) {
            //setQuery();

            var errMsg = checkValue();
            if (errMsg == '') {

                if (myDataTable) {

                    var fromName = $("#txtFormName").val();
                    var jsonStr = YAHOO.lang.JSON.stringify(myDataTable);
                    var PKeyJson = PrimaryKeyItems;
                    _FormName = fromName;
                    if (typeof (jsonStr) != "undefined") {
                        createEditor(_FormName, TableName, jsonStr, PKeyJson);
                    }
                }


            }
            else { alert(errMsg); }
        }
        var fnChkAll = function () {
            var ck = $("input[type=checkbox]");
            for (var i = 0; i < ck.length; i++) {
                if (ck[i].type == "checkbox") {
                    ck[i].checked = document.getElementById("chkAll").checked;
                    if (mDataTable._oRecordSet._records[i] != undefined) {
                        mDataTable._oRecordSet._records[i]._oData.iSun_Selected = ck[i].checked;
                    }
                }
            }
        }
        var fnCreateChkAllCheckBox = function () {

            if ((document.getElementById("chkAll")) == null) {

                var e1 = window.document.getElementById("yui-dt0-th-iSun_Selected");
                if (e1 == null) {
                    e1 = window.document.getElementById("yui-dt0-th-iSun_Selected");
                }
                if (e1 == null) {
                    return;
                }
                if (typeof (e1) != "undefined") {
                    var in1 = e1.firstChild;
                    var el = document.createElement("input");
                    el.setAttribute("type", "checkbox");
                    el.setAttribute("id", "chkAll");
                    el.setAttribute("onclick", "fnChkAll()");
                    el.setAttribute("style", "margin-left:0px;margin-top:0px;z-index:200")
                    in1.insertBefore(el);
                }
            }
        }
        var txtFormName_ChangeEvent = function (obj) {

            if (checkIsEmpty(obj)) {
                alert("您输入的表单名为空！请重新输入。");
            }
            DIF.GetIExistFormName.init(obj.value);

        }
        var checkValue = function () {
            var ErrMsg = '';
            var formName = document.getElementById("txtFormName");
            //var setTable = document.getElementById("setTable");
            if (checkIsEmpty(formName)) { ErrMsg = "您输入的表单名为空！请重新输入."; }
            //if (checkIsEmpty(setTable)) { ErrMsg = ErrMsg + "您选择入的表名为空！请重新选择."; }

            return ErrMsg;
        }
        var checkIsEmpty = function (obj) {
            var text = obj.value
            var isEmpty = false;
            if (text == '') { isEmpty = true; }
            else { isEmpty = false; }
            return isEmpty;
        }

        var setTable_ChangeEvent = function (oArgs) {
            var f = oArgs.name;
            //alert(f);
            var v = oArgs.value;
            //alert(v);
            if (v == '') { alert("您选择入的表名为空！请重新选择。"); }
            else {
                const_EntityName = v;
                getTableField(v);
            }
        }

        var getTableField = function (v) {
            var _currentParams = {
                TableName: v
            };
            $.ajax({
                type: "POST",
                url: "TableData.aspx/getTableField", //获取主表信息
                data: JSON.stringify(_currentParams),
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function (data) {
                    if (data) {
                        if (data.d) {
                            const_SolutionList = data.d;
                            SetFormValue();
                        }
                    }
                },
                error: function (err) {
                    alert(err + "err");
                }
            });
        }

        //值改变事件
        var ChangeEvent = function (oArgs) {
            var f = oArgs.name;
            //alert(f);
            var v = oArgs.value;
            //alert(v);
            setValue(f, v);
        }

        ///f=字段名 v=值
        var setValue = function (f, v) {
            var recordID = mDataTable.getSelectedRows()[0];
            var record = mDataTable.getRecord(recordID);
            record._oData[f] = v;
        }


        var ChangeSolution = function (obj) {
            //alert(obj.value);
            for (var i = 0; i < const_SolutionList.length; i++) {
                if (const_SolutionList[i].QueryId == obj.value) {
                    SetFormValue(const_SolutionList[i]);
                }
            }

            //const_SolutionList 
        }

        var SetFormValue = function () {

            var arr = const_SolutionList;
            if (arr != null) {
                myDataSource.liveData = arr;
                mDataTable.getDataSource().sendRequest(null,
        { success: mDataTable.onDataReturnInitializeTable },
        mDataTable);
            }
            // mDataTable.render();
            // document.getElementById("SolutionName").value = obj.SolutionName;
            // document.getElementById("IsDefault").checked = QueryInstance[0].IsDefault == "Y" ? true : false;
        }

    
    </script>
    
       </form>
</body>
</html>
